package cn.nio.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

//编写网络客户端程序
public class NIOClient {
    public static void main(String[] args) throws IOException {

        //1.得到一个网络通道

        SocketChannel channel = SocketChannel.open();

        //2.设置阻塞方式
        channel.configureBlocking(false);

        //3.提供服务器端的ip地址和端口号
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9999);

        //4.连接服务器

        if (!channel.connect(address)) {
            while (!channel.finishConnect()) {
                System.out.println("Client:连接服务器的同时,还可以做别的事情");
            }
        }

        new Thread(() -> {
            while (true) {
                try {
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int size = channel.read(buffer);
                    if (size > 0) {
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                    Thread.sleep(2000);
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //5.得到缓冲区,并存入数据
        String msg = "hello,Server";
        ByteBuffer writeBuffer = ByteBuffer.wrap(msg.getBytes());

        //6.发送数据
        Scanner input = new Scanner(System.in);
        while (true) {
            String s = input.nextLine();
            channel.write(ByteBuffer.wrap(s.getBytes()));
        }

    }
}
